package com.ktjy.ch15.controller;

import com.ktjy.ch15.entity.SysRole;
import com.ktjy.ch15.entity.SysUser;
import com.ktjy.ch15.service.SysRoleService;
import com.ktjy.ch15.utils.Constants;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/main/role")
public class SysRoleController extends BaseController {
    private static final Logger LOGGER = LoggerFactory.getLogger(SysRoleController.class);

    @Autowired
    private SysRoleService sysRoleService;

    @RequestMapping("/list")
    public String list(Model model) {
        try {
            List<SysRole> list = sysRoleService.findAll();
            model.addAttribute("list", list);
        } catch (Exception e) {
            LOGGER.error("SysRoleController 中的 condition 方法执行发生错误。 ", e);
            throw new RuntimeException(e);
        }
        return "role/list";
    }

    @GetMapping("/save")
    public String toSave(Model model) {
        return "role/save";
    }

    @PostMapping("/save")
    public String doSave(SysRole sysRole, HttpSession session) {
        SysUser loginUser = (SysUser) session.getAttribute(Constants.SESSION_USER);
        try {
            boolean ok = false;
            if (sysRole.getId() == null) {//新增
                sysRole.setCreatedUserId(loginUser.getId());
                sysRole.setCreatedTime(new Date());
                ok = sysRoleService.save(sysRole);
            } else {//修改
                sysRole.setUpdatedUserId(loginUser.getId());
                sysRole.setUpdatedTime(new Date());
                ok = sysRoleService.update(sysRole);
            }

            if (ok) {
                //跳转到列表;重定向到分页方法
                return redirect("/main/role/list");
            } else {
                //跳回新增页面
                return "role/save";
            }
        } catch (Exception e) {
            LOGGER.error("SysUserController 中的 save 方法执行发生错误。{} ", e);
            throw new RuntimeException(e);
        }

    }
    @GetMapping("/edit")
    public String toEdit(@RequestParam("id") Long id, Model model) {
        SysRole sysRole = null;
        try {
            sysRole = sysRoleService.findById(id);
            // 回显数据时需要 supplier，这里给个空对象避免出错
            model.addAttribute("sysRole", sysRole);
        } catch (Exception e) {
            LOGGER.error("SysUserController 中的 toEdit 方法执行发生错误。 ", e);
            throw new RuntimeException(e);
        }
        return "role/save";
    }

    @DeleteMapping("/del/{id}")
    @ResponseBody
    public Object del(@PathVariable("id") Long id) {
        Map<String,Object> map = new HashMap<String,Object>();
        try {
            boolean sum = sysRoleService.count(id);
            if (sum){
                map.put("code",501);
                map.put("msg","存在");
            }else{
                boolean ok = sysRoleService.delete(id);
                if (ok){
                    map.put("code",200);
                    map.put("msg","删除成功");
                }else {
                    map.put("code",500);
                    map.put("msg","删除失败");
                }
            }
        }catch (Exception e){
            LOGGER.info("发生错误",e);
            map.put("code",500);
            map.put("msg","发生异常");
        }
        return map;
    }

    @GetMapping("/codeExist")
    @ResponseBody
    public Object codeExist(@RequestParam("code") String code) {
        Map<String,Object> map = new HashMap<>();
        try {
            SysRole sysRole = sysRoleService.findByCode(code);
            if (sysRole != null){
                map.put("exist",1);
            }else {
                map.put("exist",0);
            }
        }catch (Exception e){
            LOGGER.error("SysUserController中的accountExists方法执行发生错误", e);
            map.put("exist",-1);
            map.put("error", "出现异常，请联系管理员处理！ ");
        }
        return map;
    }
}
